package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository//此注解一般用于描述数据逻辑层的具体实现对象，此对象要交给spring管理
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn = null;//java.sql.*
        Statement stat = null;
        ResultSet rs = null;
        String sql = "select * from tb_goods";
        //1.获取连接
        try {
            conn = dataSource.getConnection();
            //2.创建Statement对象，基于此对象发送SQL
            stat = conn.createStatement();
            //3.发送SQL，执行查询
            rs = stat.executeQuery(sql);
            // 4.处理结果集
            List<Map<String, Object>> list = new ArrayList<>();
            while (rs.next()) {//循环一次，取一行，一行记录为映射一个map
                list.add(rowMap(rs));
            }
            return list;
        } catch (SQLException throwables) {//SQLException是一种检查异常
            throwables.printStackTrace();
            throw  new RuntimeException(throwables);//非检查异常，这样
        } finally {
            //5.释放资源
            close(rs, stat, conn);
        }

    }

    private void close(ResultSet rs, Statement stat, Connection conn) {
        if (rs!=null)try {rs.close(); }catch (Exception e){e.printStackTrace();}
        if (stat!=null)try {stat.close(); }catch (Exception e){e.printStackTrace();}
        if (conn!=null)try {conn.close(); }catch (Exception e){e.printStackTrace();}
    }


    private Map<String, Object> rowMap(ResultSet rs) throws SQLException {
        Map<String, Object> rowMap=new HashMap<>();
//        rowMap.put("id", rs.getInt("id"));
//        rowMap.put("name", rs.getString("name"));
//        rowMap.put("remark", rs.getString("remark"));
//        rowMap.put("createdTime",rs.getTimestamp("createdTime"));
        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        for (int i = 0; i <columnCount; i++) {
            String columnName = resultSetMetaData.getColumnLabel(i+1);
            rowMap.put(columnName,rs.getObject(columnName));
        }
        return rowMap;
    }
}
